<template>
  <div class="app">
    <mt-header :title="navTitle" fixed>
      <mt-button v-if="backIcon" slot="left" icon="back" @click="goBack">返回</mt-button>
    </mt-header>
    <!-- router-view的视图区域 -->
    <div class="router-view-box">
      <router-view></router-view>
    </div>
    <!-- tabbar视图区域 -->
    <mt-tabbar v-model="selectedTabs" fixed>
      <mt-tab-item id="home" @click.native="handleTab">
        <i class="iconfont icon-home"></i>
        <div class="tab-text">首页</div>
      </mt-tab-item>
      <mt-tab-item id="search" @click.native="handleTab">
        <i class="iconfont icon-search"></i>
        <div class="tab-text">搜索</div>
      </mt-tab-item>
      <mt-tab-item id="shopCart" @click.native="handleTab">
        <i class="iconfont icon-shop-cart"></i>
        <div class="tab-text">购物车</div>
      </mt-tab-item>
      <mt-tab-item id="vip" @click.native="handleTab">
        <i class="iconfont icon-vip"></i>
        <div class="tab-text">会员</div>
      </mt-tab-item>
    </mt-tabbar>
  </div>
</template>

<script>
export default {
  data () {
    return {
      selectedTabs: 'home',
      backIcon: false, // 控制是否显示返回操作的视图区域
      navTitle: ''
    }
  },
  methods: {
    goBack () {
      this.$router.go(-1);
    },
    handleTab () {
      // 变更tabs,当点击的tabs和url不一致时，让其跳转到对应的tabs的路由
      this.$router.push({
        name: this.selectedTabs
      })
    },
    updateRouter (newRouter) {
      // 更新导航标题
      this.navTitle = this.$route.meta.title
      // 更新返回操作视图
      const paths = ['/home', '/search', '/vip', '/shopCart']
      if (paths.includes(newRouter.path)) {
        this.backIcon = false;
      } else {
        this.backIcon = true;
      }
    }
  },
  watch: {
    // 监听路由
    $route (newRouter, oldRouter) {
      this.updateRouter(newRouter);
    }
  },
  mounted () {
    this.updateRouter(this.$route);
  }
}
</script>

<style scoped lang="less">
  .app {
    .router-view-box {
      padding: 40px 0 47px;
    }
    .tab-text {
      margin-top: 5px;
    }
  }
</style>